package com.jetgege.ipctest;

import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.support.annotation.Nullable;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by Administrator on 2018/7/26.
 */

public class BookManagerService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();
        books.add(new Book(1,"android 艺术"));
        books.add(new Book(2,"ios 高阶"));

        new Thread(new ServiceWorker()).start();
    }

    @Override
    public void onDestroy() {
        misServiceDestoryed.set(true);
        super.onDestroy();
    }

    //书本模型列表
    private CopyOnWriteArrayList<Book> books = new CopyOnWriteArrayList<>();
    //监听列表
    private RemoteCallbackList<IOnNewBookArrivedListener> listenerList = new RemoteCallbackList<>();
    //用于判断服务是否停止
    private AtomicBoolean misServiceDestoryed = new AtomicBoolean(false);

    Binder mBinder = new IBookManager.Stub() {
        @Override
        public List<Book> getBookList() throws RemoteException {
            return books;
        }

        @Override
        public void addBook(Book book) throws RemoteException {
            books.add(book);
        }

        @Override
        public void registerListener(IOnNewBookArrivedListener listener) throws RemoteException {
            listenerList.register(listener);
        }

        @Override
        public void unregisterListener(IOnNewBookArrivedListener listener) throws RemoteException {
            listenerList.unregister(listener);
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    private class ServiceWorker implements Runnable{
        @Override
        public void run() {
            while (!misServiceDestoryed.get()){
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                int bookId =books.size()+1;
                Book newBook = new Book(bookId,"new Book #"+bookId);
                try {
                    onNewBookArrived(newBook);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }

        private void onNewBookArrived(Book newBook) throws RemoteException {
            books.add(newBook);

            final  int N = listenerList.beginBroadcast();
            for (int i=0;i<N;i++){
                IOnNewBookArrivedListener listener = listenerList.getBroadcastItem(i);
                listener.onNewBookArrived(newBook);
            }
            listenerList.finishBroadcast();
        }
    }
}
